package com.example.wacoffee_user.interceptor;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.Claims;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import com.example.wacoffee_user.utils.CurrentHoler;
import io.jsonwebtoken.Jwts;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jodd.time.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String url=request.getRequestURI().toString();
        if(url.contains("login")){
            log.info("登陆请求，放行");
            return true;
        }
        String token=request.getHeader("Authorization");
        if(token==null||token.equals("")){
            log.info("token为空，请重新登录");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        token=token.replace("Bearer ","");

        try{
            JWT jwt=JWTUtil.parseToken(token);
            if(!jwt.setKey("czwa".getBytes()).verify()){
                log.info("token解析失败，请重新登录");
                response.setStatus(HttpStatus.SC_UNAUTHORIZED);
                return false;
            }
            JWTValidator.of(jwt).validateDate();
        }catch (ValidateException e){
            e.printStackTrace();
            log.info("登陆过期啦，请重新登录");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        Claims claims=JWTUtil.parseToken(token).getPayload();
        Object id = claims.getClaim("id");
        String userId=id.toString();
        if(CurrentHoler.getCurrentId()==null){
            stringRedisTemplate.opsForValue().setIfAbsent("user:"+userId,token, Duration.of(15, ChronoUnit.MINUTES));
        }
        if(!stringRedisTemplate.hasKey("user:"+userId)){
            log.info("登陆过期啦，请重新登录");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        else stringRedisTemplate.expire("user:"+userId, Duration.of(15, ChronoUnit.MINUTES));
        log.info("用户ID: {}", id);
        CurrentHoler.set(Integer.valueOf(id.toString()));
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentHoler.remove();
    }
}
